from langchain.document_loaders import (
    Docx2txtLoader,
    TextLoader
)
import pdfplumber
from langchain.text_splitter import RecursiveCharacterTextSplitter
import re
from typing import Dict, Any
import os
import logging
import chardet

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)

class ResumeProcessor:
    def __init__(self):
        self.text_splitter = RecursiveCharacterTextSplitter(
            chunk_size=1000,
            chunk_overlap=200
        )
        
    def load_resume(self, file_path: str) -> str:
        """根据文件类型加载简历内容"""
        ext = os.path.splitext(file_path)[1].lower()
        
        if ext == '.pdf':
            try:
                text = ""
                with pdfplumber.open(file_path) as pdf:
                    for page in pdf.pages:
                        text += page.extract_text() + "\n"
                if not text.strip():
                    raise ValueError("PDF text extraction returned empty content")
                return text
            except Exception as e:
                logger.error(f"PDF extraction failed: {str(e)}")
                raise ValueError(f"Failed to extract text from PDF: {str(e)}")
        elif ext == '.docx':
            loader = Docx2txtLoader(file_path)
        elif ext == '.txt' or ext == '.doc':
            print(f"Processing text file: {file_path}")
            try:
                # 先尝试utf-8
                loader = TextLoader(file_path, encoding='utf-8')
                documents = loader.load()
                print("Successfully loaded with utf-8")
            except UnicodeDecodeError as e:
                print(f"UTF-8 decode failed: {str(e)}")
                # 尝试其他常见编码
                for encoding in ['gbk', 'gb18030', 'big5']:
                    try:
                        print(f"Trying encoding: {encoding}")
                        loader = TextLoader(file_path, encoding=encoding)
                        documents = loader.load()
                        print(f"Successfully loaded with {encoding}")
                        break
                    except UnicodeDecodeError as e:
                        print(f"{encoding} decode failed: {str(e)}")
                        continue
                else:
                    error_msg = f"无法解码文件 {file_path}，请检查文件编码"
                    print(error_msg)
                    raise ValueError(error_msg)
            except Exception as e:
                error_msg = f"处理文件 {file_path} 时出错: {str(e)}"
                print(error_msg)
                raise ValueError(error_msg)
        else:
            raise ValueError(f"Unsupported file type: {ext}")
            
        return "\n\n".join([doc.page_content for doc in documents])
    
    def clean_text(self, text: str) -> str:
        """清洗简历文本"""
        # 移除多余空格和换行
        text = re.sub(r'\s+', ' ', text).strip()
        # 移除特殊字符
        text = re.sub(r'[^\w\s\u4e00-\u9fff\-\.\,]', '', text)
        return text
        
    def standardize_resume(self, raw_text: str) -> Dict[str, Any]:
        """标准化简历数据"""
        logger.info(f"原始简历文本:\n{raw_text[:500]}...")  # 打印前500字符
        cleaned_text = self.clean_text(raw_text)
        logger.info(f"清洗后文本:\n{cleaned_text[:500]}...")
        
        # 使用更灵活的正则表达式提取关键信息
        name_patterns = [
            r'(?:姓名|名字|Name)[：:\s]*(.*?)\n',
            r'^(.*?)\s+(?:电话|手机|Phone)',
            r'个人简历[：:\s]*(.*?)\n'
        ]
        
        phone_patterns = [
            r'(?:电话|手机|Phone)[：:\s]*([\d\s\-+]+)',
            r'\b1[3-9]\d{9}\b',
            r'\b\d{3,4}[- ]?\d{7,8}\b'
        ]
        
        email_patterns = [
            r'(?:邮箱|Email)[：:\s]*([a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,})',
            r'\b[a-zA-Z0-9._%+-]+@[a-zA-Z0-9.-]+\.[a-zA-Z]{2,}\b'
        ]
        
        # 尝试多种模式匹配
        name = None
        for pattern in name_patterns:
            name = re.search(pattern, cleaned_text)
            if name: break
            
        phone = None
        for pattern in phone_patterns:
            phone = re.search(pattern, cleaned_text)
            if phone: break
            
        email = None
        for pattern in email_patterns:
            email = re.search(pattern, cleaned_text)
            if email: break
        
        # 分割文本为段落
        paragraphs = self.text_splitter.split_text(cleaned_text)
        
        result = {
            "name": name.group(1).strip() if name else "",
            "phone": phone.group(1).strip() if phone else "",
            "email": email.group(1).strip() if email else "",
            "content": paragraphs,
            "raw_text": raw_text
        }
        logger.info(f"提取结果: {result}")
        return result

    def process_resume(self, file_path: str) -> Dict[str, Any]:
        """处理简历文件"""
        raw_text = self.load_resume(file_path)
        return self.standardize_resume(raw_text)
